﻿using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using GetStartedApp.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace GetStartedApp.Views;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Array httpMethodEnumArr = Enum.GetValues(typeof(HttpMethodEnum));
        if (httpMethodEnumArr != null)
        {
            for (int i = 0; i < httpMethodEnumArr.Length; i++)
            {
                object httpMethodStr = httpMethodEnumArr.GetValue(i);
                methodComboBox.Items.Add(httpMethodStr);
            }
        }

        methodComboBox.SelectedIndex = 0;
    }

    public async void ButtonClicked(object source, RoutedEventArgs args)
    {
        Debug.WriteLine("Click!");
        using HttpClient client = new();
        client.DefaultRequestHeaders.Accept.Clear();

        var httpMethodStr = methodComboBox.SelectedValue?.ToString();
        var url = urlTextBox.Text?.ToString();
        var httpContent = new StringContent("");
        if (httpMethodStr != null && url != null)
        {
            var httpResult = await SendHttpRequest(client, httpMethodStr, url, httpContent);
            Debug.WriteLine(httpResult);

            contentTextBlock.Text = httpResult;
        }
        else
        {
            Debug.WriteLine("HttpMethod is null");
        }
    }

    private Task<string> SendHttpRequest(HttpClient client, string httpMethodStr, string url, HttpContent httpContent)
    {
        int httpMethodEnumCode = (int)Enum.Parse(typeof(HttpMethodEnum), httpMethodStr);
        Task< HttpResponseMessage> httpResponseMessageTask = httpMethodEnumCode switch
        {
            (int)HttpMethodEnum.GET => client.GetAsync(url),
            (int)HttpMethodEnum.POST => client.PostAsync(url, httpContent),
            _ => throw new Exception("")
        };
        return httpResponseMessageTask.Result.Content.ReadAsStringAsync();
    }
}